package com.cql.service.business.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cql.common.core.DO.MarkDO;
import com.cql.common.core.DO.UserDO;
import com.cql.common.core.DTO.MarkDTO;
import com.cql.common.exception.moment.MomentNotExistException;
import com.cql.common.exception.user.UserNotExistException;
import com.cql.common.utils.StringUtils;
import com.cql.mapper.MarkMapper;
import com.cql.mapper.MomentMapper;
import com.cql.mapper.UserMapper;
import com.cql.service.business.MarkService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author cql
 */
@Service
public class MarkServiceImpl extends ServiceImpl<MarkMapper, MarkDO> implements MarkService {

    @Autowired
    private MarkMapper markMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MomentMapper momentMapper;

    @Override
    public MarkDTO getMark(Long momentId, UserDO userDO) {

        /**
         * TODO 要不要权限控制呢？
         */

        if (StringUtils.isNull(userDO)) {
            throw new UserNotExistException();
        }

        if (StringUtils.isNull(momentId)) {
            throw new MomentNotExistException();
        }

        QueryWrapper<MarkDO> wrapper = new QueryWrapper<>();
        wrapper.eq("moment_id", momentId);
        wrapper.eq("user_id", userDO.getUserId());

        MarkDO markDO = markMapper.selectOne(wrapper);

        if (StringUtils.isNull(markDO)) {
            return null;
        }

        MarkDTO result = new MarkDTO();

        BeanUtils.copyProperties(markDO, result);

        /**
         * 可能不需要这两个信息
         */
        result.setUser(userMapper.selectById(markDO.getUserId()));
        result.setMomentDO(momentMapper.selectById(markDO.getMarkId()));


        return result;
    }

    @Override
    public void insertMark(MarkDO mark) {
        /**
         * 一个用户，一篇文章，只能有一个mark，1对1关系
         */
        QueryWrapper<MarkDO> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", mark.getUserId());
        wrapper.eq("moment_id", mark.getMomentId());
        MarkDO markDO = markMapper.selectOne(wrapper);
        if (StringUtils.isNull(markDO)) {
            markMapper.insert(mark);
        }
    }

    @Override
    public void deleteMark(Long markId, Long userId) {
        QueryWrapper<MarkDO> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("moment_id", markId);
        markMapper.delete(wrapper);

    }

    @Override
    public List<MarkDO> listMark(Long userId) {
        QueryWrapper<MarkDO> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return markMapper.selectList(wrapper);
    }

}
